package com.utils.redis.pipeline;

import com.utils.redis.utils.JedisSimpleUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xin.ding
 * @date 2020/9/22 15:58
 */
public class BatchOperGet {

    private static final String HOST = "redis01";
    private static final int PORT = 6379;
    private static final String PASSWORD = "redis";

    /**
     * 批量从Redis中获取数据，正常使用
     */
    public static Map<String, String> batchGetNotUsePipeline() throws Exception {
        Map<String, String> map = new HashMap<>(16);
        Jedis jedis = JedisSimpleUtils.getJedisClient();
        String keyPrefix = "normal";
        long begin = System.currentTimeMillis();
        for (int i = 1; i < 10000; i++) {
            String key = keyPrefix + "_" + i;
            String value = jedis.get(key);
            map.put(key, value);
        }
        jedis.close();

        long end = System.currentTimeMillis();
        System.out.println("not use pipeline batch get total time：" + (end - begin));
        return map;
    }

    /**
     * 批量从Redis中获取数据，使用Pipeline
     */
    public static Map<String, String> batchGetUsePipeline() throws Exception {
        Map<String, String> map = new HashMap<>(16);
        Jedis jedis = JedisSimpleUtils.getJedisClient();
        Pipeline pipelined = jedis.pipelined();
        String keyPrefix = "pipeline";

        // 使用pipeline方式批量获取数据，只能获取到value值，对应的key获取不到，我们通过一个中间map来获取key
        HashMap<String, Response<String>> intrmMap = new HashMap<>(16);
        long begin = System.currentTimeMillis();
        for (int i = 1; i < 10000; i++) {
            String key = keyPrefix + "_" + i;
            intrmMap.put(key, pipelined.get(key));
        }

        pipelined.sync();
        jedis.close();

        for (Map.Entry<String, Response<String>> entry : intrmMap.entrySet()) {
            Response<String> sResponse = entry.getValue();
            String key = entry.getKey();
            String value = sResponse.get();
            map.put(key, value);
        }

        long end = System.currentTimeMillis();
        System.out.println("use pipeline batch get total time：" + (end - begin));
        return map;
    }

    public static void main(String[] args) {
        try {
//            batchGetNotUsePipeline();
//            batchGetUsePipeline();

            Map<String, String> normalMap = batchGetNotUsePipeline();
            for (Map.Entry<String, String> entry : normalMap.entrySet()) {
                System.out.println(entry.getKey() + "=" + entry.getValue());
            }

            Map<String, String> pipelineMap = batchGetUsePipeline();
            for (Map.Entry<String, String> entry : pipelineMap.entrySet()) {
                System.out.println(entry.getKey() + "=" + entry.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

